<?php
declare(strict_types=1);

namespace app\controller\merchant;

use app\BaseController;
use think\facade\{Db, Cache};
use think\Request;

class ExpressProfitController extends BaseController
{
    /**
     * 获取商家快递利润配置
     */
    public function index(Request $request)
    {
        // 获取指定业务类型的配置
        $type = $request->param('type', 1); // 1快递 2物流 3同城配送
        
        $list = Db::name('merchant_express_company')
            ->alias('mc')
            ->join('express_company c', 'c.id = mc.express_company_id')
            ->where([
                'mc.merchant_id' => $request->merchantId,
                'c.company_type' => $type
            ])
            ->field('mc.id, mc.express_company_id, mc.first_weight_profit, mc.continued_weight_profit, 
                    mc.create_time, c.company_name, c.company_code, c.company_type')
            ->select();
            
        // 获取未配置的快递公司
        $configuredIds = array_column($list->toArray(), 'express_company_id');
        $unconfigured = Db::name('express_company')
            ->where('company_type', $type)
            ->whereNotIn('id', $configuredIds)
            ->field('id as express_company_id, company_name, company_code, company_type')
            ->select();
            
        $data = [
            'configured' => $list,
            'unconfigured' => $unconfigured
        ];
            
        return $this->success('获取成功', $data);
    }
    
    /**
     * 设置商家快递利润配置
     */
    public function save(Request $request)
    {
        $data = $this->validate($request->post(), [
            'express_company_id' => 'require|integer',
            'first_weight_profit' => 'require|float|between:0,100', // 首重利润率0-100%
            'continued_weight_profit' => 'require|float|between:0,100' // 续重利润率0-100%
        ]);
        
        Db::startTrans();
        try {
            // 检查快递公司
            $company = Db::name('express_company')
                ->where('id', $data['express_company_id'])
                ->find();
            if (!$company) {
                throw new \Exception('快递公司不存在');
            }
            
            // 更新或插入配置
            $config = Db::name('merchant_express_company')
                ->where([
                    'merchant_id' => $request->merchantId,
                    'express_company_id' => $data['express_company_id']
                ])->find();
                
            if ($config) {
                Db::name('merchant_express_company')
                    ->where('id', $config['id'])
                    ->update([
                        'first_weight_profit' => $data['first_weight_profit'],
                        'continued_weight_profit' => $data['continued_weight_profit'],
                        'update_time' => date('Y-m-d H:i:s')
                    ]);
            } else {
                Db::name('merchant_express_company')->insert([
                    'merchant_id' => $request->merchantId,
                    'express_company_id' => $data['express_company_id'],
                    'first_weight_profit' => $data['first_weight_profit'],
                    'continued_weight_profit' => $data['continued_weight_profit'],
                    'create_time' => date('Y-m-d H:i:s')
                ]);
            }
            
            // 清除缓存
            Cache::tag('express_profit')->clear();
            
            Db::commit();
            return $this->success('保存成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
    
    /**
     * 批量设置利润率
     */
    public function batchSave(Request $request)
    {
        $data = $this->validate($request->post(), [
            'type' => 'require|integer|in:1,2,3', // 1快递 2物流 3同城配送
            'first_weight_profit' => 'require|float|between:0,100',
            'continued_weight_profit' => 'require|float|between:0,100'
        ]);
        
        Db::startTrans();
        try {
            // 获取指定类型的所有快递公司
            $companies = Db::name('express_company')
                ->where('company_type', $data['type'])
                ->column('id');
                
            foreach ($companies as $companyId) {
                $config = Db::name('merchant_express_company')
                    ->where([
                        'merchant_id' => $request->merchantId,
                        'express_company_id' => $companyId
                    ])->find();
                    
                if ($config) {
                    Db::name('merchant_express_company')
                        ->where('id', $config['id'])
                        ->update([
                            'first_weight_profit' => $data['first_weight_profit'],
                            'continued_weight_profit' => $data['continued_weight_profit'],
                            'update_time' => date('Y-m-d H:i:s')
                        ]);
                } else {
                    Db::name('merchant_express_company')->insert([
                        'merchant_id' => $request->merchantId,
                        'express_company_id' => $companyId,
                        'first_weight_profit' => $data['first_weight_profit'],
                        'continued_weight_profit' => $data['continued_weight_profit'],
                        'create_time' => date('Y-m-d H:i:s')
                    ]);
                }
            }
            
            Cache::tag('express_profit')->clear();
            
            Db::commit();
            return $this->success('批量设置成功');
        } catch (\Exception $e) {
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }
} 